package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        System.out.println("文件上传方法被调用了...");

        try {
            //获取原始文件名   1.jpg
            String originalFilename = file.getOriginalFilename();
            //获取原始文件的后缀
            String endName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成一个文件名称
            String startName = UUID.randomUUID().toString();

            //url是上传成功之后的绝对网络路径
            //https://tlias-webapp.oss-cn-hangzhou.aliyuncs.com/33f659d2-d014-45cb-9ca5-52638878570b.jpg
            String url = aliOssUtil.upload(file.getBytes(), startName + endName);
            return Result.success(url);
        } catch (IOException e) {
            log.info("文件上传失败: {}",e);
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
